package com.mall.gateway.queue;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Darren
 * @date 2022-10-17 17:18
 * Description：
 */
@Component
public class HotQueue {
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 商品非热门
     */
    public static final Integer NOT_HOT = 0;
    /**
     * 已经在排队中
     */
    public static final Integer HAS_QUEUE = 204;
    /**
     * 排队成功
     */
    public static final Integer QUEUE_ING = 200;

    /**
     * 抢单排队
     *
     * @param username
     * @param id
     * @param num
     * @return
     */
    public int hotToQueue(String username, String id, Integer num) {
        // 获取商品在redis中的信息,如果商品在redis中,则是热门商品
        Boolean isHot = redisTemplate.boundHashOps("HotSeckillGoods").hasKey(id);

        // 非热门
        if (isHot != null && !isHot) {
            return NOT_HOT;
        }

        // 避免重复排队
        Long increment = redisTemplate.boundValueOps("OrderQueue" + username).increment();
        if (increment != null && increment > 1)
            return HAS_QUEUE;

        // 执行排队操作
        Map<String, Object> map = new HashMap<>(3);
        map.put("username", username);
        map.put("id", id);
        map.put("num", num);
        Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(map)).build();
        rocketMQTemplate.convertAndSend("order-queue", message);
        return QUEUE_ING;
    }
}
